<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.user_name"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
          <el-form-item label="管理员名称">
            <el-input
              v-model="searchForm.manager_name"
              placeholder="请输入管理员名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="订单ID">
            <el-input
              v-model="searchForm.order_id"
              placeholder="请输入订单ID"
              clearable
            />
          </el-form-item>
          <el-form-item label="到账金额">
            <el-input-number
              v-model="searchForm.amount[0]"
              placeholder="最小金额"
              :min="0"
              style="width: 120px"
            />
            <span style="margin: 0 8px">-</span>
            <el-input-number
              v-model="searchForm.amount[1]"
              placeholder="最大金额"
              :min="0"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item label="汇率金额">
            <el-input-number
              v-model="searchForm.rate_amount[0]"
              placeholder="最小汇率金额"
              :min="0"
              style="width: 120px"
            />
            <span style="margin: 0 8px">-</span>
            <el-input-number
              v-model="searchForm.rate_amount[1]"
              placeholder="最大汇率金额"
              :min="0"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item label="充值金额">
            <el-input-number
              v-model="searchForm.total[0]"
              placeholder="最小充值金额"
              :min="0"
              style="width: 120px"
            />
            <span style="margin: 0 8px">-</span>
            <el-input-number
              v-model="searchForm.total[1]"
              placeholder="最大充值金额"
              :min="0"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.ctime_date_range"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="x"
              style="width: 350px"
            />
          </el-form-item>
          <el-form-item label="更新时间">
            <el-date-picker
              v-model="searchForm.utime_date_range"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="x"
              style="width: 350px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <!--0:等待审核 1:等待申请人确认 2:已确认 3:审核人结算确认 4:失败-->
            <el-select
              v-model="searchForm.state"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="等待审核" :value="0" />
              <el-option label="等待申请人确认" :value="1" />
              <el-option label="已确认" :value="2" />
              <el-option label="审核人结算确认" :value="3" />
              <el-option label="失败" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card">
      <!-- 搜索表单 -->
      <div>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增入金
        </el-button>
        <span>
          <!-- <span>全部金额：</span><span class="amount"></span>
        <span>完成金额：</span><span class="amount"></span>
        <span>全部金额：</span><span class="amount"></span> -->
          <span style="margin-left: 50px">成功充值金额：</span>
          <span class="amount" style="color: red">{{ successTotal }}</span>
        </span>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column
          prop="orderID"
          label="订单号"
          width="180"
          align="center"
        />
        <el-table-column
          prop="total"
          label="充值金额"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <span>{{ row.total ? (row.total / 100).toFixed(2) : "0.00" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="rate" label="汇率" width="120" align="center">
          <template #default="{ row }">
            <span>{{ row.rate ? (row.rate / 100).toFixed(2) : "0.00" }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="usdt" label="usdt" width="120" align="center" /> -->
        <el-table-column
          prop="rateAmount"
          label="汇率金额"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <span>{{
              row.rateAmount ? (row.rateAmount / 100).toFixed(2) : "0.00"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="amount"
          label="到账金额"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <span>{{
              row.amount ? (row.amount / 100).toFixed(2) : "0.00"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="bankName"
          label="收款银行"
          width="120"
          align="center"
        />
        <el-table-column
          prop="paymentMethod"
          label="支付方式"
          width="120"
          align="center"
        />

        <el-table-column
          prop="bankNum"
          label="收款账号"
          width="120"
          align="center"
        />
        <el-table-column
          prop="userName"
          label="申请人"
          width="120"
          align="center"
        />
        <el-table-column
          prop="manage_name"
          label="审核人"
          width="120"
          align="center"
        />
        <!-- <el-table-column prop="arrivalAmount" label="到账金额" width="120" align="center">
          <template #default="{ row }">
            <span>{{ row.arrivalAmount ? row.arrivalAmount.toFixed(2) : '0.00' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="remark"
          label="备注"
          width="150"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="state"
          label="支付状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.state)">{{
              getStatusText(row.state)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="cTime"
          label="创建时间"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            <span>{{ formatTime(row.cTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="uTime"
          label="更新时间"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            <span>{{ formatTime(row.uTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="success" size="small" @click="handleOperation(row)"
              >入金操作</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增弹窗 -->
    <el-dialog
      v-model="addVisible"
      title="新增入金"
      width="500px"
      :before-close="handleCloseAdd"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="选择账户">
          <el-select
            v-model="bankID"
            placeholder="请选择账户"
            @change="handleBankChange"
          >
            <el-option
              v-for="item in bankConfigList"
              :key="item.bankUnion"
              :label="item.bankName"
              :value="item.bankUnion"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账户" prop="account">
          <el-input
            v-model="addForm.account"
            placeholder="请输入账户"
            clearable
            disabled
          />
        </el-form-item>

        <el-form-item label="银行名称" prop="bankName">
          <el-input
            v-model="addForm.bankName"
            placeholder="请输入银行名称"
            clearable
            disabled
          />
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankNum">
          <el-input
            v-model="addForm.bankNum"
            placeholder="请输入银行卡号"
            clearable
            disabled
          />
        </el-form-item>
        <el-form-item label="银行联行号" prop="bankUnion">
          <el-input
            v-model="addForm.bankUnion"
            placeholder="请输入银行联行号"
            clearable
            disabled
          />
        </el-form-item>
        <el-form-item label="汇率" prop="rate">
          <el-input
            v-model="addForm.rate"
            placeholder="请输入汇率"
            clearable
            disabled
          />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input
            v-model="addForm.amount"
            placeholder="请输入金额"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addForm.remark"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAdd">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmitAdd"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 入金操作弹窗 -->
    <el-dialog
      v-model="operationVisible"
      title="入金操作"
      width="500px"
      :before-close="handleCloseOperation"
    >
      <el-form
        ref="operationFormRef"
        :model="operationForm"
        :rules="operationRules"
        label-width="100px"
      >
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="operationForm.state">
            <el-radio :label="0">等待审核</el-radio>
            <el-radio :label="1">等待申请人确认</el-radio>
            <el-radio :label="2">已确认</el-radio>
            <el-radio :label="3">审核人结算确认</el-radio>
            <el-radio :label="4">失败</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="operationForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>
        <el-form-item label="密钥代码" prop="secretCode">
          <el-input
            v-model="operationForm.secretCode"
            placeholder="请输入密钥代码"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseOperation">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmitOperation"
            :loading="operationLoading"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {
  getBankList,
  createBank,
  rejectBank,
  getWebconfigList,
} from "@/api/system";

import { ref, onMounted, reactive } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import dayjs from "dayjs";

// 响应式数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const successTotal = ref(0);

// 搜索表单
const searchForm = ref({
  user_name: "",
  manager_name: "",
  order_id: "",
  amount: [0, 0],
  rate_amount: [0, 0],
  total: [0, 0],
  ctime_date_range: [],
  utime_date_range: [],
  state: null,
  page: 1,
  size: 10,
});

// 获取数据
const loadData = async () => {
  loading.value = true;
  try {
    // 构建请求参数，处理数组和空值
    const params: any = {
      page: currentPage.value,
      size: pageSize.value,
    };

    // 添加非空的搜索条件
    if (searchForm.value.user_name) {
      params.user_name = searchForm.value.user_name;
    }
    if (searchForm.value.manager_name) {
      params.manager_name = searchForm.value.manager_name;
    }
    if (searchForm.value.order_id) {
      params.order_id = searchForm.value.order_id;
    }
    if (
      searchForm.value.state !== null &&
      searchForm.value.state !== undefined
    ) {
      params.state = searchForm.value.state;
    }

    // 处理数组范围参数
    if (searchForm.value.amount[0] > 0 || searchForm.value.amount[1] > 0) {
      params.amount = searchForm.value.amount;
    }
    if (
      searchForm.value.rate_amount[0] > 0 ||
      searchForm.value.rate_amount[1] > 0
    ) {
      params.rate_amount = searchForm.value.rate_amount;
    }
    if (searchForm.value.total[0] > 0 || searchForm.value.total[1] > 0) {
      params.total = searchForm.value.total;
    }

    // 处理时间范围参数
    if (
      searchForm.value.ctime_date_range &&
      searchForm.value.ctime_date_range.length === 2
    ) {
      params.ctime_date_range = searchForm.value.ctime_date_range;
    }
    if (
      searchForm.value.utime_date_range &&
      searchForm.value.utime_date_range.length === 2
    ) {
      params.utime_date_range = searchForm.value.utime_date_range;
    }

    const response: any = await getBankList(params);
    if (response.code === 0) {
      tableData.value = response.data.data || [];
      total.value = response.data.total || 0;
      successTotal.value = response.data.sumSuccess.amount || 0;
    } else {
      ElMessage.error(response.message || "获取数据失败");
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 获取银行数据
const bankConfigList = ref<any>([]);
const bankID = ref(0);

const getBankData = async () => {
  try {
    const response: any = await getWebconfigList();
    if (response.code === 0) {
      bankConfigList.value = response.data.data.bankConfig || [];
      console.log(bankConfigList.value);
    } else {
      ElMessage.error(response.message || "获取数据失败");
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  }
};
getBankData();

// 处理银行选择变化
const handleBankChange = (val: any) => {
  console.log(val);

  if (val) {
    // 根据选中的bankUnion值找到对应的银行配置对象
    const selectedBank = bankConfigList.value.find(
      (item: any) => item.bankUnion === val
    );
    if (selectedBank) {
      addForm.bankName = selectedBank.bankName;
      addForm.bankUnion = selectedBank.bankUnion;
      addForm.rate = selectedBank.rate / 100;
      addForm.account = selectedBank.account;
      addForm.bankNum = selectedBank.bankNum;
    }
  }
};

// 新增入金
const addVisible = ref(false);
const submitLoading = ref(false);
const addFormRef = ref<FormInstance>();
const addForm = reactive({
  account: "",
  amount: 0,
  bankName: "",
  bankNum: 0,
  bankUnion: 0,
  rate: 0,
  remark: "",
});

// 入金操作
const operationVisible = ref(false);
const operationLoading = ref(false);
const operationFormRef = ref<FormInstance>();
const operationForm = reactive({
  id: 0,
  state: 0,
  remark: "",
  secretCode: "",
});

// 表单验证规则
const addRules: FormRules = {
  account: [{ required: true, message: "请输入账户", trigger: "blur" }],
  amount: [
    { required: true, message: "请输入金额", trigger: "blur" },
    // 不能为0
    {
      validator: (rule: any, value: number, callback: any) => {
        console.log(rule, value);
        if (value === 0) {
          callback(new Error("金额不能为0"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  bankName: [{ required: true, message: "请输入银行名称", trigger: "blur" }],
  bankNum: [{ required: true, message: "请输入银行卡号", trigger: "blur" }],
  bankUnion: [{ required: true, message: "请输入银行联行号", trigger: "blur" }],
  rate: [{ required: true, message: "请输入汇率", trigger: "blur" }],
};

// 入金操作表单验证规则
const operationRules: FormRules = {
  state: [{ required: true, message: "请选择状态", trigger: "change" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
  secretCode: [{ required: true, message: "请输入密钥代码", trigger: "blur" }],
};

// 打开新增弹窗
const handleAdd = () => {
  addVisible.value = true;
};

// 关闭新增弹窗
const handleCloseAdd = () => {
  addVisible.value = false;
  resetAddForm();
};

// 重置新增表单
const resetAddForm = () => {
  addFormRef.value?.resetFields();
  Object.assign(addForm, {
    account: "",
    amount: 0,
    bankName: "",
    bankNum: 0,
    bankUnion: 0,
  });
};

// 提交新增表单
const handleSubmitAdd = async () => {
  if (!addFormRef.value) return;

  try {
    await addFormRef.value.validate();
    submitLoading.value = true;
    // 金额转换为分
    addForm.amount = Number(addForm.amount);
    addForm.bankNum = addForm.bankNum;
    addForm.bankUnion = Number(addForm.bankUnion);
    addForm.rate = Number(addForm.rate);

    const response: any = await createBank(addForm);
    if (response.code === 0) {
      ElMessage.success("新增成功");
      addVisible.value = false;
      resetAddForm();
      loadData(); // 刷新列表
    } else {
      ElMessage.error(response.message || "新增失败");
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitLoading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 重置
const handleReset = () => {
  searchForm.value = {
    user_name: "",
    manager_name: "",
    order_id: "",
    amount: [0, 0],
    rate_amount: [0, 0],
    total: [0, 0],
    ctime_date_range: [],
    utime_date_range: [],
    state: null,
    page: 1,
    size: 10,
  };
  currentPage.value = 1;
  loadData();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadData();
};

// 时间格式化
const formatTime = (time: string | number | Date) => {
  if (!time) return "-";
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

// 状态处理
const getStatusType = (
  status: number
): "primary" | "success" | "info" | "warning" | "danger" => {
  //0:等待审核 1:等待申请人确认 2:已确认 3:审核人结算确认 4:失败

  switch (status) {
    case 0:
      return "primary";
    case 1:
      return "info";
    case 2:
      return "success";
    case 3:
      return "warning";
    case 4:
      return "danger";
    default:
      return "primary";
  }
};

const getStatusText = (status: number) => {
  //0:等待审核 1:等待申请人确认 2:已确认 3:审核人结算确认 4:失败
  switch (status) {
    case 0:
      return "等待审核";
    case 1:
      return "等待申请人确认";
    case 2:
      return "已确认";
    case 3:
      return "审核人结算确认";
    case 4:
      return "失败";
  }
};

// 入金操作
const handleOperation = (row: any) => {
  operationForm.id = row.id;
  operationForm.state = row.state || 0;
  operationForm.remark = row.remark || "";
  operationForm.secretCode = "";
  operationVisible.value = true;
};

// 关闭入金操作弹窗
const handleCloseOperation = () => {
  operationVisible.value = false;
  resetOperationForm();
};

// 重置入金操作表单
const resetOperationForm = () => {
  operationFormRef.value?.resetFields();
  Object.assign(operationForm, {
    id: 0,
    state: 0,
    remark: "",
    secretCode: "",
  });
};

// 提交入金操作
const handleSubmitOperation = async () => {
  if (!operationFormRef.value) return;

  try {
    await operationFormRef.value.validate();
    operationLoading.value = true;

    // 这里调用入金操作的API
    const response: any = await rejectBank(operationForm);
    if (response.code === 0) {
      ElMessage.success("入金操作成功");
      operationVisible.value = false;
      resetOperationForm();
      loadData(); // 刷新列表
    } else {
      ElMessage.error(response.message || "入金操作失败");
    }
    operationVisible.value = false;
    resetOperationForm();
    loadData(); // 刷新列表
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    operationLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  /* background-color: #f5f5f5; */
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  font-weight: bold;
}
.search-card {
  margin-bottom: 20px;
}
</style>
